package com.lagou.front.user.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lagou.common.result.ResponseDTO;
import com.lagou.user.api.UserRemoteService;
import com.lagou.user.api.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * @author dingchengyu
 * @date 2022/3/5 16:28
 */

@Slf4j
@Service
@RefreshScope
public class UserService {


    @Autowired
    private OAuthRemoteService oAuthRemoteService;
    @Value("${spring.oauth.client_id}")
    private String clientId;
    @Value("${spring.oauth.client_secret}")
    private String clientSecret;
    @Value("${spring.oauth.scope}")
    private String scope;
    @Value("${spring.oauth.grant_type}")
    private String grantType;

    /**
     * 发放access_token、refresh_token
     *
     * @param phone
     * @param password
     * @return
     */
    public ResponseDTO<String> createAuthToken(String phone, String password) {
        log.info("phone:{}, password:{}, scope:{}, grantType:{}, clientId:{}, clientSecret:{}", phone, password, scope, grantType, clientId, clientSecret);
        String token = null;

        try {
            token = this.oAuthRemoteService.createToken(phone, password, scope, grantType, clientId, clientSecret);
            if (StringUtils.isBlank(token)) {
                return ResponseDTO.ofError(206, "登录失败");
            }
            JSONObject jsonObject = JSON.parseObject(token);
            String resultCode = jsonObject.getString("access_token");
            if (StringUtils.isBlank(resultCode)) {
                log.info("phone:{}, jwt token is null", phone);
                return ResponseDTO.ofError(206, "登录失败(" + resultCode + ")");

            }
            return ResponseDTO.response(1, "success", token);
        } catch (Exception e) {
            log.error("", e);
            return ResponseDTO.ofError(206, "登录失败");
        }
    }
}
